//
//  PowerNumTopic.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/7/29.
//

import UIKit

class PowerNumTopic: BaseTopic {
    
    /// 底数
    var base: Double = 1
    /// 指数
    var exponential: Int = 1
    
    /// 题目 latex表达式
    var latex: String?
    /// 答案
    var answer: Double = 0.0
    /// 输入的答案
    var inputAnswer: Double?
    
    init(base: Double, exponential: Int) {
        self.base = base
        self.exponential = exponential
        
        self.latex = "\(base)^\(exponential)"
        self.answer = pow(base, Double(exponential))
    }
    
    override func setInputAnswer(answer: String?, numerator: Float = 0.0, denominator: Float = 1) {
        self.inputAnswer = Double(answer ?? "0.0")
    }
    
    override func getTopicDesc() -> String {
        return "\(base)^\(exponential) = \\; ?"
    }
    
    override func answerIsCorrect() -> Bool {
        let minAnswer = answer - 0.05
        let maxAnswer = answer + 0.05
        
        guard let tAnswer = inputAnswer else { return false }
        
        if tAnswer > minAnswer && tAnswer < maxAnswer {
            return true
        }
        
        return false
    }
    
    override func getResultDesc() -> NSMutableAttributedString {
        var sym = "√"
        var color = UIColor.black
        if !answerIsCorrect() {
            sym = "×"
            color = .red
        }
        
        let answerStr = String(format: "%.3f", answer)
        let desc = "\(base)的\(exponential)次方 = \(answerStr) (\(inputAnswer ?? 0.0)) \(sym)"
        
        let attri = NSMutableAttributedString(string: desc)
        let tmpRange = NSRange(location: desc.count - 1, length: 1)
        
        attri.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: tmpRange)
        return attri
    }
}
